<template>
  <div class="header">
    <h3>请上传你需要识别的图片</h3>
    <input type="file" @change="handleFileInput" />
  </div>
  <div class="content">
    <div class="content_left">
      <h2>待识别图片:</h2>
      <img
        ref="image"
        :src="imageUrl"
        alt=""
        width="200"
        height="100"
        v-if="imageUrl"
      />
    </div>
    <div class="content_right">
      <h2>
        识别结果:
        <p>
          <i
            class="iconfont icon-fuzhi"
            @click="handleCopy"
            title="点击复制结果"
          ></i>
        </p>
      </h2>
      <template v-if="ocrResult.length > 0">
        <p v-html="formatText(ocrResult)" v-clipboard:copy="copyContent"></p>
      </template>
    </div>
  </div>
</template>

<script>
import { ref, computed } from "vue";
import Tesseract from "tesseract.js";

export default {
  setup() {
    const imageUrl = ref("");
    const ocrResult = ref("");

    const handleFileInput = async (event) => {
      const file = event.target.files[0];
      const reader = new FileReader();
      reader.onload = async (e) => {
        // 显示图片
        imageUrl.value = e.target.result;

        // 发送图片进行OCR识别
        const response = await Tesseract.recognize(file, "chi_sim+eng");
        const rawText = response.data.text;
        ocrResult.value = rawText;
      };
      reader.readAsDataURL(file);
    };
    const copyContent = computed(() => {
      return ocrResult.value;
    });
    function formatText(text) {
      return text.replace(/\n/g, "<br>");
    }
    function handleCopy() {
      if (ocrResult.value === "")
        return ElMessage({
          showClose: true,
          message: "不能复制空内容！",
          type: "error",
        });
      ElMessage({
        showClose: true,
        message: "复制成功",
        type: "success",
      });
    }
    return {
      imageUrl,
      ocrResult,
      copyContent,
      handleFileInput,
      formatText,
      handleCopy,
    };
  },
};
</script>

<style lang="less" scoped>
.header {
  // width: 50%;
  display: flex;
  align-items: center;
  justify-content: space-around;
}

h2 {
  width: 280px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
